
package org.apli.haiam.servlet;

import com.apli.controladores.AplinfoFactoryBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apli.haiam.admin.entidades.UsuarioAdmin;
import org.apli.haiam.ejb.entidades.AdmMenu;
import org.apli.haiam.ejb.entidades.AdmSesion;
import org.apli.haiam.ejb.entidades.AdmSistema;
import org.apli.haiam.ejb.interfaces.AdministradorLoginHaiam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Permite iniciar una sesion en el sistema. 
 *
 * <H6>Soporte:HAIAM
 * <I>david_s_1086@hotmail.com,david.carranza@haiam.gob.ec</I></H6>
 *
 * @author david Carranza
 * @version 1.0 30/07/2014
 */
@WebServlet(name = "AutoLogin", urlPatterns = {"/AutoLogin"})
public class AutoLogin extends HttpServlet {

    final Logger log = LoggerFactory.getLogger(AutoLogin.class);
    private static String _SIS;
    @EJB
    private AdministradorLoginHaiam adminLogin;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            _SIS = request.getContextPath();

            cargarEjb();
            String _token = request.getParameter("skp");
            String url = request.getParameter("spu");
            Object usr = request.getSession().getAttribute("user");
            AdmSistema sistemaPrincipal = (AdmSistema) request.getServletContext().getAttribute("sistemaPrincipal");
            AdmSistema sistema = (AdmSistema) request.getServletContext().getAttribute("sistema");

            if (_token != null && _token.trim().length() > 10) {
                try {
                    log.info(_SIS + " **** AutoLogin() {} Sesión ID", _token);
                    AdmSesion token = adminLogin.getSesion(_token);
                    UsuarioAdmin user = (UsuarioAdmin) usr;
                    if (user != null && user.getSesion().getSesion().equals(token.getSesion())) {
                        log.info("**** AutoLogin() {} se encuentra ya autenticado", user.getUsername());
                    } else { // iniciar una sesión
                        log.info(_SIS + " **** AutoLogin() {} AUTENTICANDO", token.getAdmUsuario().getUsername());
                        HttpSession session = request.getSession(false);
                        try {
                            session.invalidate();
                        } catch (Exception e) {
                        }
                        String remoteAddr = request.getRemoteAddr();
                        String host = request.getRemoteHost();
                        user = (UsuarioAdmin) adminLogin.iniciarSesionToken(token, remoteAddr, host, sistema, sistemaPrincipal,null);
                        request.getSession().setAttribute("user", user);
                        request.getSession().removeAttribute("menu");
                        request.getSession().setAttribute("menu", user.getMenu());
                    }
                } catch (Exception e) {
                    log.error(_SIS + " AutoLogin() {} ", e.getMessage());
                }
            } else {
                if (usr != null) {
                    log.info(_SIS + " **** AutoLogin() Cerrando sesión en equipo LOCAL({}) y redirecionando para cerrar sesion en {}", request.getContextPath(), _SIS);
                    HttpSession session = request.getSession(false);
                    try {
                        session.invalidate();
                    } catch (Exception e) {
                    }
                }
                // carga los datos del sistema principal
                log.info(_SIS + " ----------------------------");
                List<AdmMenu> menu = null;
                try {
                    menu = adminLogin.getMenuBase(sistemaPrincipal);
                    log.info(_SIS + " AutoLogin(..) SISTEMA GLOBAL UTILIZADO {}", sistemaPrincipal);
                } catch (Exception e) {
                    try {
                        menu = adminLogin.getMenuBase(sistema);
                    } catch (Exception ex) {
                    }
                    log.info(_SIS + " AutoLogin(..) No existe sistema global ...");
                }
                request.getSession().removeAttribute("menu");
                request.getSession().setAttribute("menu", menu);
                log.info(_SIS + " ----------------------------");
                //--
            }
            try {
                log.info(_SIS + " AutoLogin() redireccionando a:{} ", url);
                response.sendRedirect(url);
            } catch (IOException e) {
                log.error(_SIS + " AutoLogin() {} ", e.getMessage());
            }

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    /**
     * Obtiene el objeto remoto.
     */
    protected void cargarEjb() {
        if (adminLogin == null) {
            String ejbPath = null;
            try {
                ResourceBundle property = getProperties();
                String ORBContext = property.getString("ORBContext");
                String ejbContextPath = property.getString("ejb.context.path.admin");
                ejbPath = ORBContext + ejbContextPath + "/AdministradorLoginBean";
                adminLogin = (AdministradorLoginHaiam) AplinfoFactoryBean.lookupBean(ejbPath, false);
//                try {
//                    adminLogin.getFechaDb();
//                } catch (Exception e) {
//                }
            } catch (Exception e) {
                log.error(_SIS + " cargarEjb() {} - {} ", ejbPath, e.getMessage());
            }
        }

    }

    protected ResourceBundle getProperties() {
        return ResourceBundle.getBundle("aplicacion");
    }
}